package mt.util;

import java.util.Calendar;
import java.util.Date;

public class IDUtil {

	/**
	 * 根据身份证号获取性别
	 * 
	 * @param pid
	 *            身份证号
	 * @return 性别 1为女0为男
	 */
	public static String getSexByPid(String pid) {
		if (pid != null
				&& (pid.trim().length() == 15 || pid.trim().length() == 18)) {
			if (pid.trim().length() == 15) {
				String pid18 = pid15To18(pid);
				if (Integer.parseInt(pid18.substring(16, 17)) % 2 == 0) {
					return "1";
				} else {
					return "0";
				}
			} else {
				if (Integer.parseInt(pid.substring(16, 17)) % 2 == 0) {
					return "1";
				} else {
					return "0";
				}
			}
		} else {
			return "0";
		}
	}

	/**
	 * 根据身份证号获取生日
	 * 
	 * @param pid
	 *            身份证号
	 */
	public static Date getBirthdayByPid(String pid)  {
		Calendar birthdayCaoendar = Calendar.getInstance();
		if (pid != null
				&& (pid.trim().length() == 15 || pid.trim().length() == 18)) {
			if (pid.trim().length() == 15) {
				String pid18 = pid15To18(pid);
				birthdayCaoendar.set(Calendar.YEAR,
						Integer.parseInt(pid18.substring(6, 10)));
				// Month 值是基于 0 的。例如，0 表示 January
				birthdayCaoendar.set(Calendar.MONTH,
						Integer.parseInt(pid18.substring(10, 12)) - 1);
				birthdayCaoendar.set(Calendar.DAY_OF_MONTH,
						Integer.parseInt(pid18.substring(12, 14)));
			} else {
				birthdayCaoendar.set(Calendar.YEAR,
						Integer.parseInt(pid.substring(6, 10)));
				// Month 值是基于 0 的。例如，0 表示 January
				birthdayCaoendar.set(Calendar.MONTH,
						Integer.parseInt(pid.substring(10, 12)) - 1);
				birthdayCaoendar.set(Calendar.DAY_OF_MONTH,
						Integer.parseInt(pid.substring(12, 14)));
			}
			return birthdayCaoendar.getTime();
		} else {
			return null;
		}
	}

	private static String pid15To18(String perIDSrc) {
		int iS = 0;
		int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8,
				4, 2 };
		String LastCode = "10X98765432";
		String perIDNew;

		perIDNew = perIDSrc.substring(0, 6);
		perIDNew += "19";
		perIDNew += perIDSrc.substring(6, 15);

		for (int i = 0; i < 17; i++) {
			iS += Integer.parseInt(perIDNew.substring(i, i + 1)) * iW[i];
		}

		int iY = iS % 11;
		perIDNew += LastCode.substring(iY, iY + 1);

		return perIDNew;
	}
	
	public static void main(String[] args) {
		String id ="350721198504074211";
		try {
			System.out.println(IDUtil.getSexByPid(id));
			System.out.println(DateTimeUtil.getYYMMDD(IDUtil.getBirthdayByPid(id)));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
